<template>
    <span class="cd-time">
        {{countTime}}
    </span>
</template>

<script>
const CD_TIME = 30 * 60 * 1000;

export default {
    props: {
        start: {
            type: String,
            default: '',
        },
    },
    data() {
        return {
            countTime: '-',
            timer: null,

            cancleTime: null,
        };
    },
    methods: {
        setCancelTime() {
            if (!this.start) return;

            var startTime = new Date(this.start),
                startTimeTime = new Date(this.start.replace(/-/g,"/")).getTime();

            this.cancleTime = startTimeTime;
        },
        setTimer() {
            this.timer = setInterval(() => {
                var nowTime = new Date().getTime(),
                    deltaTime = (this.cancleTime - nowTime) / 1000,
                    timeObj = this.calculator(deltaTime);
                
                const {day,hour,min,second} = timeObj;
                this.countTime = `${(day * 24) + hour}:${min}:${second}`;

                if (deltaTime <= 0) {
                    this.$emit('clear');
                    this.countTime = `${0}:${0}:${0}`
                    this.clearTimer();
                }
            }, 1000);
        },
        clearTimer() {
            clearTimeout(this.timer);
        },
        calculator(second){
                var sec = 1,
                    min = 60 * sec,
                    hour = 60 * min,
                    day = 24 * hour;
                return {
                    day: parseInt(second / day),
                    hour: parseInt(second % day / hour),
                    min: parseInt(second % hour / min),
                    second: parseInt(second % min),
                    timetamp: second
                }
            }
    },
    mounted() {
        this.setCancelTime();
        this.setTimer();
    },
    beforeDestroy() {
        this.clearTimer();
    },
};
</script>

<style lang="scss" scoped>
@import "@css/var.scss";
.cd-time {
    color: $primaryColor;
}

</style>